import { defineStore } from 'pinia'
import type { StudyGroup as BaseStudyGroup, GroupMember, GroupActivity } from '@/types/group'
import type { PaginationResponse } from '@/types/index'

// 扩展学习小组接口，添加isJoined属性
export interface StudyGroup extends BaseStudyGroup {
  isJoined?: boolean
}
import { getGroups, getGroupDetail, createGroup, joinGroup, leaveGroup, updateGroup, deleteGroup, getGroupMembers, createGroupActivity, getGroupActivities } from '@/api/group'

interface GroupsState {
  groups: StudyGroup[]
  group: StudyGroup | null
  members: GroupMember[]
  activities: GroupActivity[]
  pagination: PaginationResponse<StudyGroup>
  isLoading: boolean
  error: string | null
  recommendedGroups: StudyGroup[]
}

export const useGroupsStore = defineStore('groups', {
  state: (): GroupsState => ({
    groups: [],
    group: null,
    members: [],
    activities: [],
    pagination: {
      content: [],
      totalElements: 0,
      currentPage: 1,
      pageSize: 10,
      totalPages: 0
    },
    isLoading: false,
    error: null,
    recommendedGroups: []
  }),
  
  getters: {
    // 获取当前用户所在的小组
    myGroups: (state): StudyGroup[] => {
      return state.groups.filter((group: StudyGroup) => group.isJoined)
    },
    
    // 根据标签获取小组
    groupsByTag: (state) => (tag: string) => {
      if (!tag) return state.groups
      return state.groups.filter((group: StudyGroup) => 
        group.tags && group.tags.some((t: string) => t === tag)
      )
    }
  },
  
  actions: {
    // 获取小组列表
    async fetchGroups(params?: {
      keyword?: string
      category?: string
      isPublic?: boolean
      sortBy?: 'latest' | 'popular' | 'name'
      page?: number
      pageSize?: number
    }) {
      try {
        this.isLoading = true
        this.error = null
        const response = await getGroups(params || {})
        this.groups = response.content || []
        this.pagination.content = this.groups
        this.pagination.totalElements = response.totalElements || 0
        this.pagination.currentPage = 1
        this.pagination.pageSize = 10
        this.pagination.totalPages = response.totalPages || 0
        return response
      } catch (error: any) {
        this.error = error.message || '获取小组列表失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取单个小组详情
    async fetchGroupById(id: number) {
      try {
        this.isLoading = true
        this.error = null
        const response = await getGroupDetail(id)
        this.group = response
        // 获取小组成员
        await this.fetchGroupMembers(id)
        // 获取小组活动
        await this.fetchGroupActivities(id)
        return response
      } catch (error: any) {
        this.error = error.message || '获取小组详情失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 创建小组
    async createGroup(groupData: { name: string; description: string; categoryId?: number; maxMembers?: number; isPublic?: boolean }) {
      try {
        this.isLoading = true
        this.error = null
        const response = await createGroup(groupData)
        // 刷新小组列表
        await this.fetchGroups({ page: this.pagination.page, pageSize: this.pagination.pageSize })
        return response
      } catch (error: any) {
        this.error = error.message || '创建小组失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 加入小组
    async joinGroup(groupId: number) {
      try {
        this.isLoading = true
        const response = await joinGroup(groupId)
        // 更新小组状态
        const group = this.groups.find((g: StudyGroup) => g.id === groupId)
        if (group) {
          group.isJoined = true
          group.currentMembers = (group.currentMembers || 0) + 1
        }
        if (this.group && this.group.id === groupId) {
          this.group.isJoined = true
          this.group.currentMembers = (this.group.currentMembers || 0) + 1
          // 重新获取小组成员
          await this.fetchGroupMembers(groupId)
        }
        return response
      } catch (error: any) {
        this.error = error.message || '加入小组失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 退出小组
    async leaveGroup(groupId: number) {
      try {
        this.isLoading = true
        const response = await leaveGroup(groupId)
        // 更新小组状态
        const group = this.groups.find((g: StudyGroup) => g.id === groupId)
        if (group) {
          group.isJoined = false
          group.currentMembers = Math.max(0, (group.currentMembers || 0) - 1)
        }
        if (this.group && this.group.id === groupId) {
          this.group.isJoined = false
          this.group.currentMembers = Math.max(0, (this.group.currentMembers || 0) - 1)
          // 重新获取小组成员
          await this.fetchGroupMembers(groupId)
        }
        return response
      } catch (error: any) {
        this.error = error.message || '退出小组失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 更新小组信息
    async updateGroup(id: number, groupData: { name?: string; description?: string; categoryId?: number; maxMembers?: number; isPublic?: boolean }) {
      try {
        this.isLoading = true
        this.error = null
        const response = await updateGroup(id, groupData)
        // 更新当前小组详情
        if (this.group && this.group.id === id) {
          this.group = { ...this.group, ...response }
        }
        // 刷新小组列表
        await this.fetchGroups({ page: this.pagination.page, pageSize: this.pagination.pageSize })
        return response
      } catch (error: any) {
        this.error = error.message || '更新小组信息失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 删除小组
    async deleteGroup(id: number) {
      try {
        this.isLoading = true
        this.error = null
        const response = await deleteGroup(id)
        // 从列表中移除小组
        this.groups = this.groups.filter((group: StudyGroup) => group.id !== id)
        // 如果删除的是当前查看的小组，清除小组详情
        if (this.group && this.group.id === id) {
          this.group = null
          this.members = []
          this.activities = []
        }
        // 更新分页信息
        this.pagination.totalElements = Math.max(0, (this.pagination.totalElements || 0) - 1)
        return response
      } catch (error: any) {
        this.error = error.message || '删除小组失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取小组成员
    async fetchGroupMembers(groupId: number) {
      try {
        const response = await getGroupMembers(groupId)
        this.members = response
        return response
      } catch (error: any) {
        console.error('获取小组成员失败:', error)
        throw error
      }
    },
    
    // 创建小组活动
    async createGroupActivity(groupId: number, activityData: { title: string; description: string; activityType: string; startTime: string; endTime?: string }) {
      try {
        this.isLoading = true
        this.error = null
        const response = await createGroupActivity(groupId, activityData)
        // 添加到活动列表
        this.activities.unshift(response)
        return response
      } catch (error: any) {
        this.error = error.message || '创建活动失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取小组活动
    async fetchGroupActivities(groupId: number) {
      try {
        const response = await getGroupActivities(groupId, {})
        this.activities = response.content || []
        return response
      } catch (error: any) {
        console.error('获取小组活动失败:', error)
        throw error
      }
    },
    
    // 获取推荐小组
    async fetchRecommendGroups() {
      try {
        this.isLoading = true
        // 这里可以调用专门的推荐API，或者基于标签、活跃度等过滤现有小组
        const response = await getGroups({ page: 1, pageSize: 5, sortBy: 'popular' })
        this.recommendedGroups = response.content || []
        return response
      } catch (error: any) {
        console.error('获取推荐小组失败:', error)
        // 不抛出错误，避免影响主流程
        return { content: [] }
      } finally {
        this.isLoading = false
      }
    },
    
    // 清除错误
    clearError() {
      this.error = null
    },
    
    // 清除小组详情
    clearGroupDetail() {
      this.group = null
      this.members = []
      this.activities = []
    }
  }
})